//
//  GameDC.mm
//  GEngine
//
//  Created by liu dingxi on 09-8-27.
//  Copyright 2009 tencent. All rights reserved.
//


#import <UIKit/UIKit.h>
#import <OpenGLES/ES1/gl.h>

#include "iphone.h"

#include "ximage.h"
#include "GameDC.h"
#include "Texture2D.h"

UIFont* g_sysFont = nil;

GText*	GDC::PrepareText(LPCTSTR lpText, int nText, const GFont* pFont, COLOR cText)
{
	CGContextRef			context;
	void*					data;
	CGColorSpaceRef			colorSpace;
	
	NSString* string = [[NSString alloc] initWithBytes:lpText length:nText encoding:NSUTF8StringEncoding];
	
	UIFont* font = nil;
	if(pFont != NULL)
	{
		font = (UIFont*)(pFont->m_pFont);
	}
	if(font == nil)
	{
		if(g_sysFont == nil)
		{	
			CGFloat size = [UIFont systemFontSize];
			g_sysFont = [UIFont systemFontOfSize:size];
		}
		font = g_sysFont;
	}
	
	
	CGSize sz = [string sizeWithFont:font];
	
	int width = (int)sz.width;
	int height = (int)sz.height;
	
	colorSpace = CGColorSpaceCreateDeviceGray();
	data = calloc(height, width);
	context = CGBitmapContextCreate(data, width, height, 8, width, colorSpace, kCGImageAlphaNone);
	CGColorSpaceRelease(colorSpace);
	
	
	CGContextSetGrayFillColor(context, 1, 1.0);
	CGContextTranslateCTM(context, 0.0, height);
	CGContextScaleCTM(context, 1.0, -1.0); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential
	UIGraphicsPushContext(context);
		
	[string drawInRect:CGRectMake(0, 0, width, height) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
	
	UIGraphicsPopContext();
	
	CGContextRelease(context);
			
	CxImage itext;
	
	itext.Create(data, width, height, cText, 0);
	free(data);

	GText* pGText = NULL;
	CTexture2D* p = new CTexture2D;
	if(p->Load(itext))
	{
		pGText = new GText();
		pGText->m_lpData = p;
	}
	else
	{
		delete p;
	}

	[string release];

	return pGText;	
}
